package com.techsoul.module.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.techsoul.common.core.constant.ApiConstants;
import com.techsoul.common.core.exception.BusinessException;
import com.techsoul.common.core.exception.user.CaptchaException;
import com.techsoul.common.core.exception.user.CaptchaExpireException;
import com.techsoul.common.core.exception.user.UserException;
import com.techsoul.common.core.pojo.vo.PostVo;
import com.techsoul.common.core.pojo.vo.RoleVo;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.codec.AesUtils;
import com.techsoul.common.core.util.collection.SetUtils;
import com.techsoul.common.core.util.http.HttpClientUtils;
import com.techsoul.common.core.util.id.IdWorker;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.security.exception.UserPasswordNotMatchException;
import com.techsoul.common.core.manager.AsyncManager;
import com.techsoul.common.core.manager.factory.AsyncFactory;
import com.techsoul.common.core.util.MessageUtils;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.service.RedisService;
import com.techsoul.common.security.pojo.LoginUser;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.system.config.WxpayProperties;
import com.techsoul.module.system.mapper.UserMapper;
import com.techsoul.module.system.pojo.param.LoginParam;
import com.techsoul.module.system.pojo.param.OAuthParam;
import com.techsoul.module.system.pojo.param.UserWeChatSaveParam;
import com.techsoul.module.system.pojo.vo.RouterVo;
import com.techsoul.common.core.pojo.vo.MenuVo;
import com.techsoul.module.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 认证授权 Service实现
 *
 * @author liuen
 * @date 2020-12-04
 */
@Slf4j
@Service
@Transactional(readOnly = true)
public class AuthServiceImpl implements IAuthService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private WxpayProperties wxpayProperties;

    @Autowired
    private RedisService redisService;

    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private IUserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IMenuService menuService;

    @Autowired
    private IPostService postService;

    @Value("${project.token.expireTime}")
    private Long expireTime;

    @Transactional(readOnly = false)
    @Override
    public String loginAfterReg(LoginParam loginParam) {
        // APP登录时，不校验验证码

        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginParam.getUserName(), loginParam.getPassword()));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLoginLog(loginParam.getUserName(), ApiConstants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLoginLog(loginParam.getUserName(), ApiConstants.LOGIN_FAIL, e.getMessage()));
                throw new UserException(e);
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLoginLog(loginParam.getUserName(), ApiConstants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }
    @Transactional(readOnly = false)
    @Override
    public String login(LoginParam loginParam) {
        // APP登录时，不校验验证码
        if (!"APP".equals(loginParam.getLoginType())) {
            String verifyKey = ApiConstants.CAPTCHA_CODE_KEY + loginParam.getUuid();
            String captcha = redisService.getCacheObject(verifyKey);
            redisService.deleteObject(verifyKey);
            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLoginLog(loginParam.getUserName(), ApiConstants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!loginParam.getCode().equalsIgnoreCase(captcha)) {
                AsyncManager.me().execute(AsyncFactory.recordLoginLog(loginParam.getUserName(), ApiConstants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginParam.getUserName(), loginParam.getPassword()));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLoginLog(loginParam.getUserName(), ApiConstants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLoginLog(loginParam.getUserName(), ApiConstants.LOGIN_FAIL, e.getMessage()));
                throw new UserException(e);
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLoginLog(loginParam.getUserName(), ApiConstants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }


    @Transactional(readOnly = false)
    @Override
    public String wxAppletLogin(UserWeChatSaveParam params) {
        // 校验用户code
        if (StringUtils.isEmpty(params.getCode())) {
            log.error("code不能为空");
            throw new BusinessException("code不能为空");
        }
        // 从微信服务器获取openid
        String jscode2sessionStr = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
        String jscode2sessionUrl = String.format(jscode2sessionStr, wxpayProperties.getAppid(), wxpayProperties.getAppsecret(), params.getCode());
        JSONObject sessionData = JSONObject.parseObject(HttpClientUtils.get(jscode2sessionUrl));
        String openid = sessionData.getString("openid");
        if (sessionData == null || StringUtils.isBlank(openid)) {
            log.error("获取用户openid失败");
            throw new BusinessException("获取用户openid失败");
        }
        UserVo userVo = userService.findByOpenid(openid);
        if (userVo == null) {
            throw new BusinessException("请先绑定微信");
        }
        List<RoleVo> userRoles = roleService.findUserRoles(userVo.getId());
        Set<String> userPermissions = SetUtils.newHashSet(menuService.findUserPermissions(userVo.getId()));
        List<PostVo> posts = postService.findUserPosts(userVo.getId());
        LoginUser loginUser = new LoginUser(userVo, userRoles, userPermissions, posts);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(ServletUtils.getRequest()));
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        return tokenService.createToken(loginUser);
    }

    @Override
    public Map<String, Object> getAccessToken(OAuthParam params) {
        UserVo userVo = this.userService.findByAppIdAndAppSecret(params.getAppId(), params.getAppSecret());
        if (userVo == null) {
            throw new BusinessException("应用ID或密钥错误，请联系管理员");
        }
        List<RoleVo> userRoles = roleService.findUserRoles(userVo.getId());
        Set<String> userPermissions = SetUtils.newHashSet(menuService.findUserPermissions(userVo.getId()));
        LoginUser loginUser = new LoginUser(userVo, userRoles, userPermissions, new ArrayList<>());
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(ServletUtils.getRequest()));
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String token = tokenService.createToken(loginUser);
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("expireTime", loginUser.getExpireTime());
        return result;
    }

    @Override
    public LoginUser getLoginUser() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser != null) {
            UserVo userVo = loginUser.getUser();
            // 角色
            loginUser.setRoles(roleService.findUserRoles(userVo.getId()));
            // 用户权限
            Set<String> permissions = SetUtils.newHashSet();
            permissions.addAll(menuService.findUserPermissions(userVo.getId()));
            loginUser.setPermissions(permissions);
            // 岗位
            loginUser.setPosts(postService.findUserPosts(userVo.getId()));
            // 更新登录用户缓存
            tokenService.setLoginUser(loginUser);
            return loginUser;
        }
        return null;
    }

    @Override
    public List<RouterVo> getRouters() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser != null) {
            UserVo userVo = loginUser.getUser();
            List<MenuVo> menuVoList = menuService.findUserMenuTree(userVo.getId());
            return menuService.buildRouters(menuVoList);
        }
        return null;
    }

}
